#include "command.h"
#include "fileSystem.h"

std::string Cd::executeCommand(std::istringstream &iss) {
    std::string path;
    iss >> path;
    if(path.empty()) return "erred path";
    if (path == "..") { // 回退
        std::string pwd = FileSystem::GetInstance().getPwd();
        if (pwd == "/") return "erred";
        size_t lastSlashPos = pwd.find_last_of('/');
        if (lastSlashPos != std::string::npos) {
            pwd.erase(lastSlashPos);
        }
        if (pwd.empty()) pwd = "/";
        FileSystem::GetInstance().setPwd(pwd);
        return "";
    }

    if (path[0] == '/') { // 绝对路径
        if (!FileTree::GetInstance().search(path)) return "erred";
        FileSystem::GetInstance().setPwd(path);
        return "";
    }

    // 处理相对路径
    std::string pwd = FileSystem::GetInstance().getPwd();
    if (pwd == "/") pwd = "";
    path = pwd + "/" + path;
    
    if (!FileTree::GetInstance().search(path)) return "erred";
    FileSystem::GetInstance().setPwd(path);
    return "";
}

std::string Ls::executeCommand(std::istringstream &iss) {
    std::string path;
    iss >> path;
    if(path.empty()) {
        path = FileSystem::GetInstance().getPwd();
    }else {
        if (path[0] != '/'){
            path = FileSystem::GetInstance().getPwd() + "/" + path;
        }
    }
    FileTree::GetInstance().print(path);
    return "";
}

std::string Mkdir::executeCommand(std::istringstream &iss) {
    std::string path;
    iss >> path;
    if(path.empty()) {
        return "Invalid path";
    }
    if (path[0] != '/') {
        path = FileSystem::GetInstance().getPwd() + "/" + path;
    }
    
    FileTree::GetInstance().insertDir(path);
    return "";
}

std::string Touch::executeCommand(std::istringstream &iss) {
    std::string path, data;
    iss >> path;
    iss >> data;
    if(path.empty()) {
        return "Invalid path";
    }
    if (path[0] != '/') {
        path = FileSystem::GetInstance().getPwd() + "/" + path;
    }
    
    if (!FileTree::GetInstance().insertFile(path, data)){
        return "Failed to create file";
    }
    return "";
}

std::string Cat::executeCommand(std::istringstream &iss) {
    std::string path;
    iss >> path;
    if(path.empty()) {
        return "Invalid path";
    }
    if (path[0] != '/') {
        path = FileSystem::GetInstance().getPwd() + "/" + path;
    }
    
    uint32_t idx = FileTree::GetInstance().search(path);
    if (idx == 0) {
        return "Failed to read file";
    }
    std::string data = IOControlLayer::GetInstance().read_file(idx);
    std::cout << data << std::endl;
    return std::string();
}
